package com.checker.springcloud.controller;

import com.checker.springcloud.entity.CommonResult;
import com.checker.springcloud.entity.Payment;
import com.checker.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Value("${server.port}")
    String port;

    @Autowired
    DiscoveryClient discoveryClient;

    @RequestMapping(value = "/payment", method = RequestMethod.POST)
    public CommonResult insertPayment(@RequestBody Payment payment) {
        int result = paymentService.insertPaument(payment);

        log.info("结果：" + result);

        if (result > 0) {
            return new CommonResult(200, "插入数据库成功: " + port, result);
        } else {
            return new CommonResult(444, "插入数据库失败");
        }
    }

    @RequestMapping(value = "/payment/{id}", method = RequestMethod.GET)
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);

        log.info("结果：" + payment);

        if (payment != null) {
            return new CommonResult(200, "获取数据成功: " + port, payment);
        } else {
            return new CommonResult(444, "获取数据失败");
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info(service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" +
                    instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri()
            );
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return port;
    }

    @GetMapping("/payment/timeout")
    public String paymentFeignTimeout() {

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }
}
